package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public User findById(String id) {
        return userDao.findById(id);
    }

    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        userDao.save(user);
    }

    public void update(User user) {
        userDao.update(user);
    }

    public void delete(String id) {
        userDao.delete(id);
    }

    //分页
    public PageInfo findAll(int page, int size, String companyId) {
        //1、设置分页参数
        PageHelper.startPage(page,size);
        //2、调用dao查询列表
        List<User> list = userDao.findAll(companyId);
        //3、构造返回值PageInfo
        return new PageInfo(list);
    }

    //根据用户id查询用户具有的所有角色id
    public List<String> findRoleIdsByUserId(String id) {
        return userDao.findRoleIdsByUserId(id);
    }

    //分配角色
    public void changeRole(String userId, String[] roleIds) {
        //根据userid，删除用户角色中间表数据
        userDao.deleteUserRole(userId);
        //循环roleIds
        for (String roleId : roleIds) {
            //向用户角色中间表保存数据
            userDao.saveUserRole(userId,roleId);
        }

    }

    //根据email查询用户
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }
}
